<template>
  <div class="task-detail-container">
    <div class="detail-header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item><a href="/">首页</a></el-breadcrumb-item>
        <el-breadcrumb-item><a href="/inspection/task">巡检任务</a></el-breadcrumb-item>
        <el-breadcrumb-item>任务详情</el-breadcrumb-item>
      </el-breadcrumb>
      <div class="header-title">
        <h1>巡检任务详情</h1>
      </div>
    </div>

    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="task-info-card">
          <div class="task-basic-info">
            <div class="info-row">
              <div class="info-item">
                <label class="info-label">任务名称：</label>
                <span class="info-value">{{ taskDetail.taskName }}</span>
              </div>
              <div class="info-item">
                <label class="info-label">任务状态：</label>
                <el-tag :type="statusMap[taskDetail.status] || 'info'">
                  {{ statusText[taskDetail.status] || '未知状态' }}
                </el-tag>
              </div>
            </div>
            
            <div class="info-row">
              <div class="info-item">
                <label class="info-label">设备名称：</label>
                <span class="info-value">{{ taskDetail.deviceName || '未知设备' }}</span>
              </div>
              <div class="info-item">
                <label class="info-label">任务类型：</label>
                <span class="info-value">{{ taskDetail.taskType === 1 ? '计划任务' : '临时任务' }}</span>
              </div>
            </div>

            <div class="info-row">
              <div class="info-item">
                <label class="info-label">负责人ID：</label>
                <span class="info-value">{{ taskDetail.assigneeId || '未分配' }}</span>
              </div>
              <div class="info-item">
                <label class="info-label">负责人：</label>
                <span class="info-value">{{ taskDetail.assigneeName || '未分配' }}</span>
              </div>
            </div>

            <div class="info-row">
              <div class="info-item">
                <label class="info-label">开始时间：</label>
                <span class="info-value">{{ formatDate(taskDetail.startTime) }}</span>
              </div>
              <div class="info-item">
                <label class="info-label">结束时间：</label>
                <span class="info-value">{{ formatDate(taskDetail.endTime) || '未完成' }}</span>
              </div>
            </div>

            <div class="info-row">
              <div class="info-item full-width">
                <label class="info-label">任务描述：</label>
                <div class="info-value description-content">{{ taskDetail.description || '无描述' }}</div>
              </div>
            </div>

            <div class="info-row">
              <div class="info-item">
                <label class="info-label">创建时间：</label>
                <span class="info-value">{{ formatDate(taskDetail.created) }}</span>
              </div>
              <div class="info-item">
                <label class="info-label">更新时间：</label>
                <span class="info-value">{{ formatDate(taskDetail.updated) }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 巡检记录信息 -->
      <el-col :span="24" v-if="inspectionRecords.length > 0">
        <el-card class="inspection-records-card">
          <div slot="header" class="card-header">
            <span>相关巡检记录</span>
          </div>
          <el-table :data="inspectionRecords" border style="width: 100%">
            <el-table-column prop="id" label="记录ID" width="80"></el-table-column>
            <el-table-column prop="inspectionTime" label="巡检时间" width="180">
              <template slot-scope="scope">
                {{ formatDate(scope.row.inspectionTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="巡检结果" width="120">
              <template slot-scope="scope">
                <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                  {{ scope.row.status === 1 ? '正常' : '异常' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="remarks" label="巡检备注" show-overflow-tooltip></el-table-column>
            <el-table-column prop="auditStatus" label="审核状态" width="120">
              <template slot-scope="scope">
                <el-tag :type="getAuditStatusType(scope.row.auditStatus)">
                  {{ getAuditStatusText(scope.row.auditStatus) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="auditRemarks" label="审核备注" show-overflow-tooltip width="150"></el-table-column>
            <el-table-column prop="auditTime" label="审核时间" width="180">
              <template slot-scope="scope">
                {{ scope.row.auditTime ? formatDate(scope.row.auditTime) : '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="inspectorName" label="巡检人" width="120"></el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <div class="action-buttons">
      <el-button @click="goBack">返回列表</el-button>
    </div>
  </div>
</template>

<script>
import inspectionTaskApi from '@/api/inspection-task'
import inspectionRecordApi from '@/api/inspection-record'
import userApi from '@/api/sys-user'

export default {
  name: 'InspectionTaskDetail',
  data() {
    return {
      taskDetail: {
        id: '',
        taskName: '',
        taskType: 1,
        deviceId: '',
        deviceName: '',
        assigneeId: '',
        assigneeName: '',
        startTime: '',
        endTime: '',
        status: 1,
        description: '',
        created: '',
        updated: ''
      },
      inspectionRecords: [],
      statusMap: {
        1: 'warning',
        2: 'primary',
        3: 'success',
        4: 'danger'
      },
      statusText: {
        1: '待执行',
        2: '执行中',
        3: '已完成',
        4: '已逾期'
      }
    }
  },
  created() {
    this.taskId = this.$route.params.id
    this.fetchTaskDetail()
    this.fetchInspectionRecords()
  },
  methods: {
      // 获取审核状态样式
      getAuditStatusType(status) {
        const typeMap = {
          0: 'info',
          1: 'warning',
          2: 'success',
          3: 'danger'
        }
        return typeMap[status] || 'info'
      },
      
      // 获取审核状态文本
      getAuditStatusText(status) {
        const textMap = {
          0: '待审核',
          1: '审核中',
          2: '审核通过',
          3: '审核拒绝'
        }
        return textMap[status] || '未知状态'
      },
    
    // 获取任务详情
    fetchTaskDetail() {
      inspectionTaskApi.detail(this.taskId)
        .then(res => {
          if (res.code === 200 && res.data) {
            this.taskDetail = res.data
            // 获取负责人名称
            if (this.taskDetail.assigneeId) {
              this.fetchAssigneeName(this.taskDetail.assigneeId)
            } else {
              this.taskDetail.assigneeName = '未分配'
            }
          } else {
            this.$message.error(res.msg || '获取任务详情失败')
          }
        })
        .catch(error => {
          this.$message.error('获取任务详情失败：' + (error.message || '未知错误'))
          console.error('获取任务详情失败:', error)
        })
    },
    
    // 获取负责人名称
    fetchAssigneeName(userId) {
      userApi.query({ id: userId })
        .then(res => {
          if (res.code === 200 && res.data?.records?.[0]) {
            console.log(res.data.records[0].username,"获取负责人信息成功");
            // this.taskDetail.assigneeName = res.data.records[0].username || '未知负责人'
            this.$set(this.taskDetail, 'assigneeName', res.data.records[0].username || '未知负责人')
            
          } else {
            this.taskDetail.assigneeName = '未知负责人'
          }
        })
        .catch(error => {
          console.error('获取负责人信息失败:', error)
          this.taskDetail.assigneeName = '未知负责人'
        })
    },
    
    // 获取巡检记录
    fetchInspectionRecords() {
      inspectionRecordApi.query({ taskId: this.taskId })
        .then(res => {
          if (res.code === 200 && res.data) {
            this.inspectionRecords = res.data.records || []
            // 为每个巡检记录获取巡检人名称
            this.inspectionRecords.forEach(record => {
              if (record.inspectorId) {
                this.fetchInspectorName(record)
              }
            })
          }
        })
        .catch(error => {
          console.error('获取巡检记录失败:', error)
        })
    },
    
    // 获取巡检人名称
    fetchInspectorName(record) {
      userApi.query({ id: record.inspectorId })
        .then(res => {
          if (res.code === 200 && res.data?.records?.[0]) {
            this.$set(record, 'inspectorName', res.data.records[0].username || '未知巡检人')
          } else {
            this.$set(record, 'inspectorName', '未知巡检人')
          }
        })
        .catch(error => {
          console.error('获取巡检人信息失败:', error)
          this.$set(record, 'inspectorName', '未知巡检人')
        })
    },
    
    // 格式化日期
    formatDate(date) {
      if (!date) return ''
      const d = new Date(date)
      const year = d.getFullYear()
      const month = String(d.getMonth() + 1).padStart(2, '0')
      const day = String(d.getDate()).padStart(2, '0')
      const hours = String(d.getHours()).padStart(2, '0')
      const minutes = String(d.getMinutes()).padStart(2, '0')
      const seconds = String(d.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    
    // 返回列表页面
    goBack() {
      this.$router.push('/inspection/task')
    }
  }
}
</script>

<style scoped>
.task-detail-container {
  padding: 20px;
}

.detail-header {
  margin-bottom: 20px;
}

.header-title h1 {
  margin: 10px 0;
  color: #303133;
  font-size: 24px;
}

.task-info-card,
.inspection-records-card {
  margin-bottom: 20px;
}

.task-basic-info {
  padding: 10px 0;
}

.info-row {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 16px;
}

.info-item {
  flex: 1;
  min-width: 300px;
  display: flex;
  align-items: flex-start;
  margin-bottom: 10px;
}

.info-item.full-width {
  min-width: 100%;
}

.info-label {
  font-weight: 500;
  color: #606266;
  width: 100px;
  flex-shrink: 0;
}

.info-value {
  color: #303133;
  flex: 1;
}

.description-content {
  line-height: 1.6;
  white-space: pre-wrap;
  word-break: break-word;
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
  border-left: 3px solid #409eff;
}

.card-header {
  font-weight: 500;
  color: #303133;
  font-size: 16px;
}

.action-buttons {
  margin-top: 30px;
  text-align: center;
}

@media (max-width: 768px) {
  .info-item {
    min-width: 100%;
  }
  
  .detail-header {
    padding: 0 10px;
  }
  
  .task-detail-container {
    padding: 10px;
  }
}
</style>